package com.rsa.boot.controller;

import cn.hutool.core.util.RandomUtil;
import com.rsa.boot.Dao.UserMapper;
import com.rsa.boot.entiry.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * @author tanghailan
 * @date 2020-10-21 17:10
 */
@RequestMapping("user")
@Controller
public class UserController {
    @Resource
    private UserMapper userMapper;

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    /**
     * 处理登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public  String login(String username,String password){
        //获取主体对象
        Subject subject  = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/login.jsp";
    }


    /**
     * 注册
     * @return
     */
    @RequestMapping("register")
    public String register(User user){
        String salt = RandomUtil.randomString(8);
        //将随机盐保存到对象
        user.setSalt(salt);
        //明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt ,1024);
        user.setPassword(md5Hash.toHex());
        try {
            userMapper.insert(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }
}
